package com.svs.system.service;

import com.svs.common.constant.UserConstants;
import com.svs.common.support.Convert;
import com.svs.common.utils.StringUtils;
import com.svs.framework.base.service.CrudService;
import com.svs.system.domain.SysDictType;
import com.svs.system.mapper.master.SysDictDataDao;
import com.svs.system.mapper.master.SysDictTypeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典 业务层处理
 *
 * @author dujianqiao
 */
@Service
public class SysDictTypeService extends CrudService<SysDictTypeDao, SysDictType> {
	@Autowired
	private SysDictTypeDao dictTypeMapper;

	@Autowired
	private SysDictDataDao dictDataMapper;

	public List<SysDictType> findAll() {
		return selectAllList(new SysDictType()) ;
	}

	/**
	 * 批量删除字典类型
	 *
	 * @param ids
	 *            需要删除的数据
	 * @return 结果
	 */
	public int deleteDictTypeByIds(String ids) throws Exception {
		String[] dictIds = Convert.toStrArray(ids);
		for (String dictIdStr : dictIds) {
			Long dictId = Long.valueOf(dictIdStr);
			SysDictType dictType = selectByPrimaryKey(dictId);
			if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
				throw new Exception(String.format("%1$s已分配,不能删除", dictType.getDictName()));
			}
		}

		return dictTypeMapper.deleteByPrimaryKeys(dictIds);
	}



	/**
	 * 修改保存字典类型信息
	 *
	 * @param dictType
	 *            字典类型信息
	 * @return 结果
	 */
	public int updateDictType(SysDictType dictType) {
		SysDictType oldDict = dictTypeMapper.selectByPrimaryKey(dictType.getDictId());
		dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType());
		return dictTypeMapper.updateByPrimaryKeySelective(dictType);
	}

	/**
	 * 校验字典类型称是否唯一
	 *
	 * @param dictType
	 *            字典类型
	 * @return 结果
	 */
	public String checkDictTypeUnique(SysDictType dict) {
		Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
		SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
		if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
			return UserConstants.DICT_TYPE_NOT_UNIQUE;
		}
		return UserConstants.DICT_TYPE_UNIQUE;
	}
}
